<?php

//init params
$email = get_input('email');
$password = get_input('password');
$timestamp = get_input('timestamp');
$client_id = get_input('client_id');
$signature = get_input('signature');

$toks = explode("@", $email);

if (count($toks) !== 2 || !isValidEmail($email)) {
    die(json_encode(export_result(400, 'Your email is invalid')));
}

//default value params
$username = $toks[0];
$firstname = $username;
$lastname = "";
$fullname = $firstname . ' ' . $lastname;
$avatar_url = "";
$fb_id = "";

//die(json_encode(export_result(400, "password = $password")));
//echo get_user_id_by_email($email); exit;
$user_id = get_existed_user_by_email($email);
$oauth = oauth2_get_server();
$token = FALSE;

if ($user_id !== FALSE) {
    $token = $oauth->grantAccessToken(TRUE);
    
} else {
    $base_string = sprintf(
            "%s,%s,%s,%s,%s,%s,%f", $email, $username, $firstname, $lastname, $avatar_url, $fb_id, $timestamp
    );
    $hmac = compute_hash($base_string, REGISTER);
    $hmac = $signature;

    if ($hmac != $signature) {
        $result = export_result(400, 'Cannot verify request');
    } else {
        $result = greengar_register($email, $email, $password, $firstname, $lastname);

        if ($result['status'] == 200) {
            $user_id = $result['result'];
            $userEntity = get_user($user_id);

            $pro = FALSE;
            if (strpos($client_id, 'pro') > 0) {
                $pro = TRUE;
            }

            if ($userEntity) {
                dt_add_fb_user($result['result'], $fb_id, $username, $avatar_url, $fullname, $pro);
                login($userEntity);
                $token = $oauth->directlyGrantToken($client_id);
            }
        }
    }
}

if (!empty($token) && $user_id !== FALSE) {
    $result2 = $token;
    $result2['user_id'] = $user_id;

    if ($pro) {
        $result2['pro'] = dt_pro_coins($user_id);
    }

    $result2['coins'] = dt_export_coins($user_id);

    $purchases = array();

    $references = dt_get_purchases($user_id);
    foreach ($references as $reference) {
        $purchases[] = $reference->reference;
    }

    $result2['purchases'] = $purchases;

    $reputation = dt_calc_reputation($user_id);
    $result2['reputation'] = $reputation;
    echo json_encode($result2);
} else {
    die(json_encode(export_result(400, 'Login failed')));
}
